var express = require("express");
var router = express.Router();
const userModel = require("../../models/userModel");
const adModel = require("../../models/adModel");
const JWT = require("../../utils/JWT");

// 获取首页广告轮播图数据
router.get("/ads", (req, res) => {
  adModel
    .find({ is_hot: true })
    .select({ __v: 0 })
    .sort({ time: -1 })
    .limit(5)
    .then((data) => {
      return res.json({
        code: 200,
        data: data,
        msg: "获取信息成功",
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 登录操作
router.post("/login", (req, res) => {
  let { userName, password } = req.body;
  userModel
    .findOne({ userName: userName, password: password })
    .then((data) => {
      if (!data) {
        return res.json({
          code: "2002",
          msg: "用户名或密码错误",
          data: null,
        });
      } else {
        // 生成token(用户信息,有效时间7天)
        const token = JWT.generate(
          {
            _id: data._id,
            username: data.userName,
          },
          "7d"
        );
        res.header("Authorization", token); //同时将token在响应头中返回给前端
        return res.json({
          code: 200,
          msg: "登录成功",
          data: {
            userName: data.userName,
            token: token,
          },
        });
      }
    })
    .catch((err) => {
      console.log(err);
      res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
      return;
    });
});

// 用户注册
router.post("/register", (req, res) => {
  let { userName } = req.body;
  userModel.find({ userName: userName }, (err, data) => {
    if (data.length > 0) {
      return res.json({
        code: "2002",
        msg: "用户已存在！",
        data: null,
      });
    } else {
      userModel
        .create({ ...req.body })
        .then((data) => {
          return res.json({
            code: 200,
            msg: "注册成功",
            data: null,
          });
        })
        .catch((err) => {
          res.status(500).send("注册失败, 请稍后再试");
        });
    }
  });
});

// 获取用户信息
router.get("/user/:userName", (req, res) => {
  let userName = req.params.userName;
  if (userName === "undefined") {
    return res.json({
      code: 200,
      msg: "没有该用户",
      data: {},
    });
  } else {
    userModel
      .findOne({ userName: userName })
      .select({ _v: 0 })
      .then((data) => {
        if (data.length === 0) {
          return res.json({
            code: 200,
            msg: "用户信息为空",
            data: data,
          });
        }
        return res.json({
          code: 200,
          msg: "获取用户信息成功",
          data: data,
        });
      })
      .catch((err) => {
        res.json({
          code: "1001",
          msg: "数据库读取失败~~~",
          data: null,
        });
        return;
      });
  }
});

// 更新用户信息
router.post("/user/update", (req, res) => {
  let { userName } = req.body;
  userModel
    .updateOne({ userName: userName }, { ...req.body })
    .then((data) => {
      if (!data.acknowledged) {
        return res.json({
          code: -1,
          msg: "没有找到该用户",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "用户信息修改成功~",
        data: null,
      });
    })
    .catch((err) => {
      res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
      return;
    });
});

// 修改用户密码
router.post("/user/update/password", (req, res) => {
  let { userName, password } = req.body;
  userModel
    .updateOne({ userName }, { password })
    .then((result) => {
      if (result.matchedCount == 0) {
        return res.json({
          code: -1,
          msg: "没有找到该用户",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "用户密码修改成功~",
        data: null,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 充值余额
router.post("/user/money", async (req, res) => {
  let { userName, money } = req.body;
  let user = await userModel.findOne({ userName });
  money += user.money;
  userModel
    .updateOne({ userName }, { money })
    .then((result) => {
      if (result.matchedCount == 0) {
        return res.json({
          code: -1,
          msg: "没有找到该用户",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "充值成功~",
        data: null,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 用户头像上传
// router.post("/files/upload",upload.single("file"), (req,res) => {
//   // 需要返回图片的访问地址   域名+文件名
//   const url = "http://localhost:3000/files/upload/" + req.file.filename
//   return res.json({
//     url:url
//   })
// })
// router.post("/files/upload", (req, res) => {
//   console.log(req.files[0]);
//   let oldName = req.files[0].filename; //获取名字
//   let originalname = req.files[0].originalname; //originnalname其实就是你上传时候文件起的名字
//   //给新名字加上原来的后缀
//   let newName = originalname;
//   fs.renameSync("./public/upload/" + oldName, "./public/upload/" + newName); //改图片的名字注意此处一定是一个路径，而不是只有文件名
//   res.send({
//     err: 0,
//     url: "http://localhost:3000/upload/" + newName,
//   });
// });

module.exports = router;
